//
//  HelpsViewController.swift
//  weile
//
//  Created by LKM on 16/12/13.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit
import SnapKit

class HelpsViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource  {
    
    var tableview: UITableView!
    
    
    
    var mListFooterLoadView :ListFooterLoadView!
    var refreshControl:UIRefreshControl!
    //    var data:ArticlesTo?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableview = UITableView()
        tableview.backgroundColor = UIColor.clear
        
        self.view.addSubview(tableview)
        
        tableview.snp.makeConstraints { (cm:ConstraintMaker) in
            cm.top.equalTo(topLayoutGuide.snp.bottom)
            cm.bottom.equalToSuperview()
            cm.left.equalToSuperview()
            cm.right.equalToSuperview()
        }
        
        
        mListFooterLoadView = ListFooterLoadView.createView();
        self.tableview.tableFooterView=mListFooterLoadView;
        
        self.tableview.register(UINib(nibName:"HelpsItem", bundle: nil), forCellReuseIdentifier: "ArticlesItem")
        
        //tableview参数设置
        tableview.rowHeight = 50;//NewArticlesItem.getHeigth()//98.7//8+82+8+0.7
        tableview.separatorStyle = .singleLine
        tableview.delegate=self;
        tableview.dataSource = self;
        //tableview参数设置  end
        
        // 添加刷新控件
        refreshControl = UIRefreshControl()
        //        refreshControl.attributedTitle = NSAttributedString(string: "松开后自动刷新")
        tableview.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(loadData(_:)), for: .valueChanged)
        // 添加刷新控件 end
        
        if loadData(false){
            refreshControl.beginRefreshing()
        }
        
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    
    
    var listData: [HelpsTo] = Array();//
    var curPage = 1;//第一开始
    var isLoadIng = false;//是否加载中
    var isLoadAppending = false;//是否加载更多数据
    var hasMoreData=true;//是否有更多数据
    
    @discardableResult
    func loadData(_ isLoadAppend :Bool) -> Bool{
        if isLoadIng {
            return isLoadAppend == isLoadAppending;
        }
        self.isLoadAppending=isLoadAppend;
        isLoadIng=true
        
        if(isLoadAppend){
            mListFooterLoadView.setAppending()
        }else{
            mListFooterLoadView.setRefreing()
        }
        
        let taskSerialNumber=Api.getHelps(preTaskSerialNumber: nil){ (re:ResponEntity) in
            self.isLoadIng=false;
            if(re.isSuccess()){
                //                self.data = re.data as? ArticlesTo;
                let articlelist = re.data as? [HelpsTo];
                
                //数据是那些----
                let hasListData = !(CollectionHelp.isEmpty( articlelist )) //!(self.data?.prolist == nil);
                if(self.isLoadAppending){
                    self.curPage += hasListData ? 1 : 0;
                }else{
                    self.listData.removeAll();
                    self.curPage = 1;
                }
                self.listData += articlelist ?? Array();
                
                self.hasMoreData = hasListData
                if(self.hasMoreData){//这个是针对这个搜索，后台没做分页的情况
                    //打于等于20就是有下一页
                    self.hasMoreData = CollectionHelp.size(articlelist) >= LKMAPIListPageSize;
                }
                //没有更多数据了
                self.mListFooterLoadView.setNone(hasNextPage: hasListData)
                //数据是那些----end
                
                self.tableview.reloadData()
            }else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg);
            }
            self.refreshControl.endRefreshing()
        }
        taskAlls.append(taskSerialNumber);
        
        return true;
    }
    
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }
    
    
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let homeCell = tableView.dequeueReusableCell(withIdentifier: "ArticlesItem")! //as! NewArticlesItem//ArticlesItem
        homeCell.selectionStyle = .default
        
     
        let o = self.listData[(indexPath as NSIndexPath).row]
        (homeCell.findViewWithTag( tag: 1) as! UILabel ).setText(str: o.Title)
        
        let count:Int=self.tableView( tableView, numberOfRowsInSection:1);
        if(indexPath.row+1>=count){
            //加载更多数据
            if hasMoreData{
                //一般到显示倒数第二个就会去加载
                loadData(true);
            }
            
        }
        
        
        return homeCell
    }
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let o = self.listData[(indexPath as NSIndexPath).row]
        
        ActivityRequest.goHelpDetailController(navigationController!, o.Id!);
//        ActivityRequest.goArticleDetailController(navigationController!,o.Id ?? "");
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

import Foundation
import SwiftyJSON

//lkm
class HelpsTo: NSObject {
    
    var ClassId: Int?;//"597"
    var Content: String?;//"<p style=\"margin: 0px; color: rgb(117, 117, 117); line-height: 1.7; font-family: 'Helvetica Neue', Helvetica, Arial, 'Microsoft Yahei', 'Hiragino Sans GB', 'Heiti SC', 'WenQuanYi Micro Hei', sans-serif; font-size: 14px;\">\r\n\t注册会员了解并同意：只要注册会员点击&ldquo;同意&rdquo;按钮并完成注册，注册会员就已接受了本注册会员协议及万商汇公布的各项服务规则（包括填写实名的联系方式等等），并愿意受其约束。如果发生纠纷，注册会员不得以未仔细阅读为由进行抗辩。</p>\r\n"
    var Content_e: String?;//""
    var Id: String?;//"49"
    var SortId: Int?;//"0"
    var Title: String?;//"服务协议"
    var Title_e: String?;//""
    
    //dict["data"].dictionaryObject  dict是JSON
    /**
     *jsons: nil → nil
     isNotEmpty: 如果字典是空的话 那么就返回nil
     */
    init?(jsons: [String: JSON]?,isNotEmpty:Bool=false) {
        super.init()
        if(jsons == nil){
            return nil
        }
        if(isNotEmpty && jsons!.isEmpty){
            return nil
        }
        if let dict = jsons{
            
            self.ClassId = dict["ClassId"]?.int;//"597"
            self.Content = dict["Content"]?.string;//"<p style=\"margin: 0px; color: rgb(117, 117, 117); line-height: 1.7; font-family: 'Helvetica Neue', Helvetica, Arial, 'Microsoft Yahei', 'Hiragino Sans GB', 'Heiti SC', 'WenQuanYi Micro Hei', sans-serif; font-size: 14px;\">\r\n\t注册会员了解并同意：只要注册会员点击&ldquo;同意&rdquo;按钮并完成注册，注册会员就已接受了本注册会员协议及万商汇公布的各项服务规则（包括填写实名的联系方式等等），并愿意受其约束。如果发生纠纷，注册会员不得以未仔细阅读为由进行抗辩。</p>\r\n"
            self.Content_e = dict["Content_e"]?.string;//""
            self.Id = dict["Id"]?.string;//"49"
            self.SortId = dict["SortId"]?.int;//"0"
            self.Title = dict["Title"]?.string;//"服务协议"
            self.Title_e = dict["Title_e"]?.string;//""
        }
    }
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToList(json js: JSON?)->[HelpsTo]?{
        if(js == nil){
            return nil;
        }
        let json = js!
        if let items = json.array {
            var results = [HelpsTo]()
            for item in items {
                //空还加个屁啊  json为“[]” 时 这是不会为空的。除非直接来了个nil
                let result = HelpsTo(jsons: item.dictionary ?? [:] )!
                results.append(result)
            }
            return results;
        }
        return [HelpsTo]()
    }
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToMap(json js: JSON?)->Dictionary<String,HelpsTo>?{
        if(js == nil){
            return nil;
        }
        let json = js!
        if let items = json.dictionary {
            var results = Dictionary<String,HelpsTo>()
            for (key, value)  in items {
                //取值的时候本身就是可选类型啊,所以这里不用跟数组一样确保不为nil
                let result = HelpsTo(jsons: value.dictionary )
                results[key] = result
            }
            return results;
        }
        return Dictionary<String,HelpsTo>()
    }
    
}

